/**
 * Copyright 2020 OPSLI 快速开发平台 https://www.opsli.com
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package org.opsli.modulars.business.patrolStationRecord.web;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.opsli.api.web.business.patrolStationRecord.PatrolStationRecordRestApi;
import org.opsli.api.wrapper.business.patrolStation.PatrolStationModel;
import org.opsli.api.wrapper.business.patrolStationRecord.PatrolStationRecordModelReport;
import org.opsli.api.wrapper.business.valveRepair.ValveRepairModel;
import org.opsli.common.annotation.RequiresPermissionsCus;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.opsli.api.base.result.ResultVo;
import org.opsli.common.annotation.ApiRestController;
import org.opsli.common.annotation.EnableLog;
import org.opsli.common.utils.OutputStreamUtil;
import org.opsli.common.utils.WrapperUtil;
import org.opsli.core.base.controller.BaseRestController;
import org.opsli.core.msg.CoreMsg;
import org.opsli.core.persistence.Page;
import org.opsli.core.persistence.querybuilder.QueryBuilder;
import org.opsli.core.persistence.querybuilder.WebQueryBuilder;
import org.opsli.core.utils.ExcelUtil;
import org.opsli.core.utils.UserUtil;
import org.opsli.modulars.business.app.web.ZkUtils;
import org.opsli.modulars.business.patrolRecordEXCEL.entity.PatrolRecord;
import org.opsli.modulars.business.patrolRecordEXCEL.service.impl.PatrolRecordServiceImpl;
import org.opsli.modulars.business.patrolRecordEXCEL.web.PatrolRecordController;
import org.opsli.modulars.business.patrolStation.entity.PatrolStation;
import org.opsli.modulars.business.patrolStation.mapper.PatrolStationMapper;
import org.opsli.modulars.business.patrolStation.service.IPatrolStationService;
import org.opsli.plugins.excel.exception.ExcelPluginException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

import org.opsli.modulars.business.patrolStationRecord.entity.PatrolStationRecord;
import org.opsli.api.wrapper.business.patrolStationRecord.PatrolStationRecordModel;
import org.opsli.modulars.business.patrolStationRecord.service.IPatrolStationRecordService;

/**
 * 巡点记录 Controller
 *
 * @author zk
 * @date 2021-09-18 10:29:42
 */
@Api(tags = PatrolStationRecordRestApi.TITLE)
@Slf4j
@ApiRestController("/business/patrolStationRecord")
public class PatrolStationRecordRestController extends BaseRestController<PatrolStationRecord, PatrolStationRecordModel, IPatrolStationRecordService>
    implements PatrolStationRecordRestApi {

    @Value("${opsli.fileUrl}")
    private  String fileUrl;
    @Value("${opsli.filePath}")
    private  String filePath;

    protected Class<PatrolStationRecordModelReport> modelClazzReport;

    @Autowired
    private IPatrolStationService patrolStationService;

    @Autowired
    private PatrolStationMapper psMapper;

    @Autowired
    private PatrolRecordServiceImpl prsl;

    /**
    * 巡点记录 查一条
    * @param model 模型
    * @return ResultVo
    */
    @ApiOperation(value = "获得单条巡点记录", notes = "获得单条巡点记录 - ID")
    @RequiresPermissions("patrolstationrecord_select")
    @Override
    public ResultVo<PatrolStationRecordModel> get(PatrolStationRecordModel model) {
        // 如果系统内部调用 则直接查数据库
        if(model != null && model.getIzApi() != null && model.getIzApi()){
            model = IService.get(model);
        }
        return ResultVo.success(model);
    }

    @Override
    public ResultVo<Map> getFile(String id){
        Map map=new HashMap();
        PatrolStationRecordModel model=IService.get(id);
        List<Map> list=new ArrayList<Map>();
        if(ZkUtils.isNotBlank(model.getRecordPic())){
            String[] arr=model.getRecordPic().split(",");
            for(String s:arr){
                Map datamap=new HashMap();
                datamap.put("src",fileUrl+s);
                list.add(datamap);
            }
        }
        map.put("pic",list);
        if(ZkUtils.isNotBlank(model.getRecordVideo())){
            map.put("video", fileUrl+model.getRecordVideo());
        }else{
            map.put("video", "");
        }
        return ResultVo.success(map);
    }

    /**
    * 巡点记录 查询分页
    * @param pageNo 当前页
    * @param pageSize 每页条数
    * @param request request
    * @return ResultVo
    */
    @ApiOperation(value = "获得分页数据", notes = "获得分页数据 - 查询构造器")
    @RequiresPermissions("patrolstationrecord_select")
    @Override
    public ResultVo<?> findPage(Integer pageNo, Integer pageSize, HttpServletRequest request) {

        Map<String,String[]> queryMap = new LinkedHashMap(request.getParameterMap());
        //查询当前devid的公司  EQ相等  LIKE模糊查询
        queryMap.put("devid_EQ",new String[]{UserUtil.getSysUser().getCompanyId()});
        QueryBuilder<PatrolStationRecord> queryBuilder = new WebQueryBuilder<>(entityClazz, queryMap);
        Page<PatrolStationRecord, PatrolStationRecordModel> page = new Page<>(pageNo, pageSize);
        page.setQueryWrapper(queryBuilder.build());
        page = IService.findPage(page);

        return ResultVo.success(page.getPageData());
    }

    @Override
    public ResultVo<?> findPageReport(Integer pageNo, Integer pageSize, HttpServletRequest request) {

        Map<String,String[]> queryMap = new LinkedHashMap(request.getParameterMap());
        //查询当前devid的公司  EQ相等  LIKE模糊查询
        queryMap.put("devid_EQ",new String[]{UserUtil.getSysUser().getCompanyId()});
        QueryBuilder<PatrolStationRecord> queryBuilder = new WebQueryBuilder<>(entityClazz, queryMap);
        Page<PatrolStationRecord, PatrolStationRecordModel> page = new Page<>(pageNo, pageSize);
        page.setQueryWrapper(queryBuilder.build());
        page = IService.findPage(page);
        List<PatrolStationModel> stations=patrolStationService.findList(UserUtil.getSysUser().getCompanyId());
        if(page.getPageData().getRows()!=null&&page.getPageData().getRows().size()>0){
            Map<String,Object> map=new HashMap<String,Object>();
            for(PatrolStationModel p:stations){
                map.put(p.getId(),p.getType());
            }
            List<PatrolStationRecordModel> list=(List<PatrolStationRecordModel>)page.getPageData().getRows();
            List<PatrolStationRecordModel> mlist=new ArrayList<PatrolStationRecordModel>();
            for(PatrolStationRecordModel model:list){
               /* PatrolStationRecordModel stationModel=patrolStationService.get(model.getValveId());
                model.setValveName(stationModel.getStationName());*/
               Object o=map.get(model.getStationId());
               if(o!=null){
                   String type=o.toString();
                   if(type.equals("1")||type.equals("2")){
                       String description="";
                       if(model.getLeakageCondition()==0){
                           description="无泄漏";
                       }else{
                           description="无泄漏";
                       }
                       if(model.getHygieneCondition()==0){
                           description+=",卫生情况良好";
                       }else{
                           description+=",无泄漏";
                       }
                       if(model.getSinkCondition()==0){
                           description+=",无塌陷";
                       }else{
                           description+=",出现塌陷";
                       }
                       if(model.getDamageCondition()==0){
                           description+=",无井盖破损";
                       }else{
                           description+=",出现井盖破损";
                       }
                       if(model.getOccupyCondition()==0){
                           description+=",无占压";
                       }else{
                           description+=",出现占压";
                       }
                       if(model.getBuryCondition()==0){
                           description+=",无掩埋";
                       }else{
                           description+=",出现掩埋";
                       }
                       model.setDescription(description);
                       mlist.add(model);
                   }
               }

            }
            page.setList(mlist);
        }
        /*page.setQueryWrapper(queryBuilder.build());
        page = IService.findPage(page);*/

        return ResultVo.success(page.getPageData());
    }


    @Override
    public ResultVo<?> findPageTy(Integer pageNo, Integer pageSize, HttpServletRequest request) {

        Map<String,String[]> queryMap = new LinkedHashMap(request.getParameterMap());
        //查询当前devid的公司  EQ相等  LIKE模糊查询
        queryMap.put("devid_EQ",new String[]{UserUtil.getSysUser().getCompanyId()});
        queryMap.put("stationType_EQ",new String[]{"4"});
        QueryBuilder<PatrolStationRecord> queryBuilder = new WebQueryBuilder<>(entityClazz, queryMap);
        Page<PatrolStationRecord, PatrolStationRecordModel> page = new Page<>(pageNo, pageSize);
        page.setQueryWrapper(queryBuilder.build());
        page = IService.findPage(page);
        List<PatrolStationModel> stations=patrolStationService.findList(UserUtil.getSysUser().getCompanyId());
        if(page.getPageData().getRows()!=null&&page.getPageData().getRows().size()>0){
            Map<String,Object> map=new HashMap<String,Object>();
            for(PatrolStationModel p:stations){
                map.put(p.getId(),p);
            }
            List<PatrolStationRecordModel> list=(List<PatrolStationRecordModel>)page.getPageData().getRows();
            List<PatrolStationRecordModel> mlist=new ArrayList<PatrolStationRecordModel>();
            for(PatrolStationRecordModel model:list){
                Object o=map.get(model.getStationId());
                if(o!=null){

                    PatrolStationModel type=(PatrolStationModel)o;
                    if(type.getType().equals("4")){
                        String description="";
                        if(model.getCondition1()==0){
                            description="外观"+"正常";
                        }else if(model.getCondition1()==1){
                            description="锈蚀";
                        }else{
                            description="无门";
                        }
                        if(model.getLeakageCondition()==0){
                            description+=",漏气";
                        }else{
                            description+=",未漏气";
                        }
                        if(model.getCondition2()==0){
                            description+=",切断正常";
                        }else{
                            description+=",切断不正常";
                        }
                        if(model.getCondition3()==0){
                            description+=",调压正常";
                        }else{
                            description+=",调压不正常";
                        }
                        if(model.getHygieneCondition()==0){
                            description+=",卫生情况良好";
                        }else{
                            description+=",有杂物";
                        }
                        if(model.getCondition4()==0){
                            description+=",压力表正常";
                        }else{
                            description+=",压力表不正常";
                        }
                        if(model.getCondition5()==0){
                            description+=",地埋管道不漏气";
                        }else{
                            description+=",地埋管道漏气";
                        }

                        if(ZkUtils.isNotBlank(model.getCondition6())){
                            description+=","+model.getCondition6();
                        }
                        model.setDescription(description);
                        mlist.add(model);
                    }
                }

            }
            page.setList(mlist);
        }
        /*page.setQueryWrapper(queryBuilder.build());
        page = IService.findPage(page);*/

        return ResultVo.success(page.getPageData());
    }

    @ApiOperation(value = "大屏调压柜调转巡点记录页面", notes = "大屏调转巡点记录页面 - 查询构造器")
    @Override
    public ResultVo<?> dpCabint(Integer pageNo, Integer pageSize, String id, HttpServletRequest request) {

        //根据名称查出id在去表里查stationId
/*        System.out.println(id);
        PatrolStationModel stationModel=psMapper.findListByLocation("123","3",id);*/

        Map<String,String[]> queryMap = new LinkedHashMap(request.getParameterMap());
        //查询当前devid的公司  EQ相等  LIKE模糊查询
        queryMap.put("devid_EQ",new String[]{"123"});
        queryMap.put("stationId_EQ",new String[]{id});
        QueryBuilder<PatrolStationRecord> queryBuilder = new WebQueryBuilder<>(entityClazz, queryMap);
        Page<PatrolStationRecord, PatrolStationRecordModel> page = new Page<>(pageNo, pageSize);
        page.setQueryWrapper(queryBuilder.build());
        page = IService.findPage(page);

        return ResultVo.success(page.getPageData());
    }

    /**
    * 巡点记录 新增
    * @param model 模型
    * @return ResultVo
    */
    @ApiOperation(value = "新增巡点记录数据", notes = "新增巡点记录数据")
    @RequiresPermissions("patrolstationrecord_insert")
    @EnableLog
    @Override
    public ResultVo<?> insert(PatrolStationRecordModel model) {
        // 调用新增方法
        IService.insert(model);
        return ResultVo.success("新增巡点记录成功");
    }

    /**
    * 巡点记录 修改
    * @param model 模型
    * @return ResultVo
    */
    @ApiOperation(value = "修改巡点记录数据", notes = "修改巡点记录数据")
    @RequiresPermissions("patrolstationrecord_update")
    @EnableLog
    @Override
    public ResultVo<?> update(PatrolStationRecordModel model) {
        // 调用修改方法
        IService.update(model);
        return ResultVo.success("修改巡点记录成功");
    }


    /**
    * 巡点记录 删除
    * @param id ID
    * @return ResultVo
    */
    @ApiOperation(value = "删除巡点记录数据", notes = "删除巡点记录数据")
    @RequiresPermissions("patrolstationrecord_update")
    @EnableLog
    @Override
    public ResultVo<?> del(String id){
        IService.delete(id);
        return ResultVo.success("删除巡点记录成功");
    }

    /**
    * 巡点记录 批量删除
    * @param ids ID 数组
    * @return ResultVo
    */
    @ApiOperation(value = "批量删除巡点记录数据", notes = "批量删除巡点记录数据")
    @RequiresPermissions("patrolstationrecord_update")
    @EnableLog
    @Override
    public ResultVo<?> delAll(String ids){
        String[] idArray = Convert.toStrArray(ids);
        IService.deleteAll(idArray);
        return ResultVo.success("批量删除巡点记录成功");
    }


    /**
    * 巡点记录 Excel 导出
    * 注：这里 RequiresPermissionsCus 引入的是 自定义鉴权注解
    *
    * 导出时，Token认证和方法权限认证 全部都由自定义完成
    * 因为在 导出不成功时，需要推送错误信息，
    * 前端直接走下载流，当失败时无法获得失败信息，即使前后端换一种方式后端推送二进制文件前端再次解析也是最少2倍的耗时
    * ，且如果数据量过大，前端进行渲染时直接会把浏览器卡死
    * 而直接开启socket接口推送显然是太过浪费资源了，所以目前采用Java最原始的手段
    * response 推送 javascript代码 alert 提示报错信息
    *
    * @param request request
    * @param response response
    */
    @ApiOperation(value = "导出Excel", notes = "导出Excel")
    @EnableLog
    @Override
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        try {

            XSSFWorkbook wb = new XSSFWorkbook(new FileInputStream(filePath+"report-template.xls"));

// 根据页面index 获取sheet页

            XSSFSheet sheet = wb.getSheet("Sheet1");
            Map<String,String[]> queryMap = new LinkedHashMap(request.getParameterMap());
            queryMap.put("devid_EQ",new String[]{UserUtil.getSysUser().getCompanyId()});
            QueryBuilder<PatrolStationRecord> queryBuilder = new WebQueryBuilder<>(entityClazz, queryMap);
            List<PatrolStationRecordModelReport> modelList = Lists.newArrayList();
            QueryWrapper<PatrolStationRecord> queryWrapper=queryBuilder.build();
            List<PatrolStationRecord> entityList = IService.findList(queryWrapper);
            List<PatrolStationModel> stations=patrolStationService.findList(UserUtil.getSysUser().getCompanyId());
            if(entityList!=null&&entityList.size()>0){
                Map<String,Object> map=new HashMap<String,Object>();
                for(PatrolStationModel p:stations){
                    map.put(p.getId(),p.getType());
                }
                Integer sort=1;
                for(PatrolStationRecord model:entityList){
                    Object o=map.get(model.getStationId());
                    if(o!=null){
                        String type=o.toString();
                        if(type.equals("1")||type.equals("2")){
                            String description="";
                            if(model.getLeakageCondition()==0){
                                description="无泄漏";
                            }else{
                                description="无泄漏";
                            }
                            if(model.getHygieneCondition()==0){
                                description+=",卫生情况良好";
                            }else{
                                description+=",无泄漏";
                            }
                            if(model.getSinkCondition()==0){
                                description+=",无塌陷";
                            }else{
                                description+=",出现塌陷";
                            }
                            if(model.getDamageCondition()==0){
                                description+=",无井盖破损";
                            }else{
                                description+=",出现井盖破损";
                            }
                            if(model.getOccupyCondition()==0){
                                description+=",无占压";
                            }else{
                                description+=",出现占压";
                            }
                            if(model.getBuryCondition()==0){
                                description+=",无掩埋";
                            }else{
                                description+=",出现掩埋";
                            }
                            PatrolStationRecordModelReport report=new PatrolStationRecordModelReport();
                            report.setDescription(description);
                            report.setSortNumber(sort);
                            sort++;
                            report.setUserName(model.getUserName());
                            report.setStationName(model.getStationName());
                            report.setLastTime(model.getLastTime());
                            modelList.add(report);
                        }

                    }

                }
            }
            if(modelList!=null&&modelList.size()>0){
                for (int i = 1; i <=modelList.size(); i++) {
                    XSSFRow row = sheet.createRow(i + 1);

// 创建HSSFCell对象 设置单元格的值

                    row.createCell(0).setCellValue(modelList.get(i-1).getSortNumber());

                    row.createCell(1).setCellValue(modelList.get(i-1).getStationName());

                    row.createCell(2).setCellValue(modelList.get(i-1).getUserName());

                    row.createCell(3).setCellValue(modelList.get(i-1).getLastTime());

                    row.createCell(4).setCellValue(modelList.get(i-1).getDescription());
                }
            }


// 输出Excel文件

            OutputStream output = response.getOutputStream();

            response.reset();

// 设置文件头

            response.setHeader("Content-Disposition",

                    "attchement;filename=" + new String(("阀井巡检报表"+ZkUtils.getDateStr().substring(0,10)+".xls").getBytes("gb2312"), "ISO8859-1"));

            response.setContentType("application/msexcel");

            wb.write(output);

            wb.close();

        } catch (Exception e) {

            e.printStackTrace();

        }

        // 当前方法
       /* Method method = ReflectUtil.getMethodByName(this.getClass(), "exportExcel");
        Map<String,String[]> queryMap = new LinkedHashMap(request.getParameterMap());
        //查询当前devid的公司  EQ相等  LIKE模糊查询
        queryMap.put("devid_EQ",new String[]{UserUtil.getSysUser().getCompanyId()});
        QueryBuilder<PatrolStationRecord> queryBuilder = new WebQueryBuilder<>(entityClazz, queryMap);
// 计时器
        TimeInterval timer = DateUtil.timer();
        String msgInfo;
        ResultVo<?> resultVo;
        List<PatrolStationRecordModel> modelList = Lists.newArrayList();
        QueryWrapper<PatrolStationRecord> queryWrapper=queryBuilder.build();
        try {
            if(queryWrapper != null){
                // 导出数量限制 -1 为无限制
                Integer exportMaxCount = globalProperties.getExcel().getExportMaxCount();
                if(exportMaxCount != null && exportMaxCount > -1){
                    // 获得数量 大于 阈值 禁止导出， 防止OOM
                    int count = IService.count(queryWrapper);
                    if(count > exportMaxCount){
                        String maxError = StrUtil.format(CoreMsg.EXCEL_HANDLE_MAX.getMessage(), count,
                                exportMaxCount);
                        // 超出最大导出数量
                        throw new ExcelPluginException(CoreMsg.EXCEL_HANDLE_MAX.getCode(), maxError);
                    }
                }


                List<PatrolStationRecord> entityList = IService.findList(queryWrapper);
                List<PatrolStationModel> stations=patrolStationService.findList(UserUtil.getSysUser().getCompanyId());
                if(entityList!=null&&entityList.size()>0){
                    Map<String,Object> map=new HashMap<String,Object>();
                    for(PatrolStationModel p:stations){
                        map.put(p.getId(),p.getType());
                    }
                    Integer sort=1;
                    for(PatrolStationRecord model:entityList){
                        Object o=map.get(model.getStationId());
                        if(o!=null){
                            String type=o.toString();
                            if(type.equals("1")||type.equals("2")){
                                String description="";
                                if(model.getLeakageCondition()==0){
                                    description="无泄漏";
                                }else{
                                    description="无泄漏";
                                }
                                if(model.getHygieneCondition()==0){
                                    description+=",卫生情况良好";
                                }else{
                                    description+=",无泄漏";
                                }
                                if(model.getSinkCondition()==0){
                                    description+=",无塌陷";
                                }else{
                                    description+=",出现塌陷";
                                }
                                if(model.getDamageCondition()==0){
                                    description+=",无井盖破损";
                                }else{
                                    description+=",出现井盖破损";
                                }
                                if(model.getOccupyCondition()==0){
                                    description+=",无占压";
                                }else{
                                    description+=",出现占压";
                                }
                                if(model.getBuryCondition()==0){
                                    description+=",无掩埋";
                                }else{
                                    description+=",出现掩埋";
                                }
                                PatrolStationRecordModel report=new PatrolStationRecordModel();
                                report.setDescription(description);
                              *//*  report.setSortNumber(sort);*//*
                                sort++;
                                report.setUserName(model.getUserName());
                                report.setStationName(model.getStationName());
                                report.setLastTime(model.getLastTime());
                                modelList.add(report);
                            }

                        }

                    }
                }
                // 转化类型
               *//* modelList = WrapperUtil.transformInstance(entityList, modelClazz);*//*

            }
            // 导出Excel
            ExcelUtil.getInstance().writeExcel(response, modelList ,"zz","sheet", modelClazz , ExcelTypeEnum.XLSX);
            // 花费毫秒数
            long timerCount = timer.interval();
            // 提示信息
            msgInfo = StrUtil.format(CoreMsg.EXCEL_EXPORT_SUCCESS.getMessage(), modelList.size(),
                    DateUtil.formatBetween(timerCount));
            // 导出成功
            resultVo = ResultVo.success(msgInfo);
            resultVo.setCode(CoreMsg.EXCEL_EXPORT_SUCCESS.getCode());
        } catch (ExcelPluginException e) {
            // 花费毫秒数
            long timerCount = timer.interval();
            // 提示信息
            msgInfo = StrUtil.format(CoreMsg.EXCEL_EXPORT_ERROR.getMessage(), DateUtil.formatBetween(timerCount), e.getMessage());
            // 导出失败
            resultVo = ResultVo.error(CoreMsg.EXCEL_EXPORT_ERROR.getCode(), msgInfo);
        }finally {
            // 清空list
            modelList.clear();
        }
        // 记录导出日志
        log.info(msgInfo);

        // 导出异常
        if(!resultVo.isSuccess()){
            // 无权访问该方法
            OutputStreamUtil.exceptionResponse(resultVo.getMsg(), response);
        }*/

       /* super.excelExport(PatrolStationRecordRestApi.SUB_TITLE, queryBuilder.build(), response, method);*/
    }


    //调压箱报表导出
    @Override
    public void exportExcelTy(HttpServletRequest request, HttpServletResponse response) {
        String devid=UserUtil.getSysUser().getCompanyId();
        String StartTime="";
        String endTime="";
        Map<String,String[]> queryMap = new LinkedHashMap(request.getParameterMap());
        System.out.println(JSON.toJSONString(queryMap));
        String FORMAT_STRING = "yyyy-MM-dd HH:mm:ss";
        String[] REPLACE_STRING = new String[]{"GMT+0800", "GMT+08:00"};
        String SPLIT_STRING = "(中国标准时间)";
        Object o1=queryMap.get("lastTime_BEGIN");
        if(o1!=null){
            String[] arr=(String[])o1;
            StartTime=arr[0];
            StartTime = StartTime.split(Pattern.quote(SPLIT_STRING))[0].replace(REPLACE_STRING[0], REPLACE_STRING[1]);
            SimpleDateFormat sf1 = new SimpleDateFormat("E MMM dd yyyy HH:mm:ss z", Locale.US);
            try {
                Date date = sf1.parse(StartTime);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                StartTime = sdf.format(date);
            }catch (Exception e){

            }


        }
        Object o2=queryMap.get("lastTime_END");
        if(o2!=null){
            String[] arr=(String[])o2;
            endTime=arr[0];
            endTime = endTime.split(Pattern.quote(SPLIT_STRING))[0].replace(REPLACE_STRING[0], REPLACE_STRING[1]);
            SimpleDateFormat sf1 = new SimpleDateFormat("E MMM dd yyyy HH:mm:ss z", Locale.US);
            try {
                Date date = sf1.parse(endTime);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                endTime = sdf.format(date);
            }catch (Exception e){

            }
        }
        String stationName="";
        Object o3=queryMap.get("stationName_LIKE");
        if(o3!=null){
            String[] arr=(String[])o3;
            stationName=arr[0];
        }
        String userName="";
        Object o4=queryMap.get("userName_LIKE");
        if(o4!=null){
            String[] arr=(String[])o4;
            userName=arr[0];
        }
        //查询所有数据
        List l = prsl.getPatrolRecord(devid, StartTime, endTime,userName,stationName);
        //将调压箱编号存入集合，以此判断有几个调压箱
        TreeSet tr = new TreeSet();
        for (int n = 0; n < l.size(); n++) {
            PatrolRecord p = (PatrolRecord) l.get(n);
            tr.add(p.getStationName());
        }
        //将不同调压箱的巡检记录，分别存入集合
        List l2 = new ArrayList();
        for (Iterator iter = tr.iterator(); iter.hasNext(); ) {
            String a1Name = (String) iter.next();
            List l1 = new ArrayList();
            for (int b = 0; b < l.size(); b++) {
                PatrolRecord b1 = (PatrolRecord) l.get(b);
                String b1Name = b1.getStationName();
                if (b1Name.equals(a1Name)) {
                    l1.add(l.get(b));
                }
            }
            l2.add(l1);
        }

        PatrolRecordController s = new PatrolRecordController();
        //输出文件流
        OutputStream output = null;
        try {
            output = response.getOutputStream();
            response.reset();
            response.setHeader("Content-Disposition",
                    "attchement;filename=" + new String(("调压箱巡检记录" + ZkUtils.getDateStr().substring(0, 10) + ".xls").getBytes("gb2312"), "ISO8859-1"));
            response.setContentType("application/msexcel");
        } catch (IOException e) {
            e.printStackTrace();
        }
        HSSFWorkbook book = null;
        try {
            book = new HSSFWorkbook(s.getExcelFile(l2));
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        try {
            book.write(output);
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        try {
            output.flush();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        try {
            output.close();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }

    /**
    * 巡点记录 Excel 导入
    * 注：这里 RequiresPermissions 引入的是 Shiro原生鉴权注解
    * @param request 文件流 request
    * @return ResultVo
    */
    @ApiOperation(value = "导入Excel", notes = "导入Excel")
    @RequiresPermissions("patrolstationrecord_import")
    @EnableLog
    @Override
    public ResultVo<?> importExcel(MultipartHttpServletRequest request) {
        return super.importExcel(request);
    }

    /**
    * 巡点记录 Excel 下载导入模版
    * 注：这里 RequiresPermissionsCus 引入的是 自定义鉴权注解
    * @param response response
    */
    @ApiOperation(value = "导出Excel模版", notes = "导出Excel模版")
    @RequiresPermissionsCus("patrolstationrecord_import")
    @Override
    public void importTemplate(HttpServletResponse response) {
        // 当前方法
        Method method = ReflectUtil.getMethodByName(this.getClass(), "importTemplate");
        super.importTemplate(PatrolStationRecordRestApi.SUB_TITLE, response, method);
    }




}
